﻿using System;
using System.Text;
using System.Web;
using System.Xml;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace CKS.EBE
{
    /// <summary>
    /// adds auto discovery functionality for blogging software
    /// http://cyber.law.harvard.edu/blogs/gems/tech/rsd.html
    /// </summary>
    public class RsdHandler : IHttpHandler
    {

        #region IHttpHandler Members
        /// <summary>
        /// IsReusable implmentation for IHttpHandler
        /// </summary>
        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// generate response
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string blogUrl = SPContext.Current.Web.Url;
                context.Response.ContentType = "text/xml";
                using (var rsdTextWriter = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
                {
                    rsdTextWriter.Formatting = Formatting.Indented;
                    rsdTextWriter.WriteStartDocument();

                    // Rsd tag
                    rsdTextWriter.WriteStartElement("rsd");
                    rsdTextWriter.WriteAttributeString("version", "1.0");

                    // Service 
                    rsdTextWriter.WriteStartElement("service");
                    rsdTextWriter.WriteElementString("engineName", "Enhanced Blog Edition 2.5");
                    rsdTextWriter.WriteElementString("engineLink", "http://www.codeplex.com/cks");
                    rsdTextWriter.WriteElementString("homePageLink", blogUrl);

                    // APIs
                    rsdTextWriter.WriteStartElement("apis");

                    // MetaWeblog
                    rsdTextWriter.WriteStartElement("api");
                    rsdTextWriter.WriteAttributeString("name", "MetaWeblog");
                    rsdTextWriter.WriteAttributeString("preferred", "true");
                    rsdTextWriter.WriteAttributeString("apiLink", blogUrl + "/metaweblog.ashx");
                    rsdTextWriter.WriteAttributeString("blogID", blogUrl);
                    rsdTextWriter.WriteEndElement();

                    // End APIs
                    rsdTextWriter.WriteEndElement();

                    // End Service
                    rsdTextWriter.WriteEndElement();

                    // End Rsd
                    rsdTextWriter.WriteEndElement();

                    rsdTextWriter.WriteEndDocument();
                }
            }
            catch (Exception ex)
            {
                Trace.Write("Error in ProcessRequest: " + ex);
            }
        }

        #endregion
    }
}
